import $cookie from 'spore-kit-cookie/cookie'
const GUID_KEY = 'guid'

// 使用 try 包装存取 cookie 和 localstorage
// 是因为私密模式下存取方法调用会触发失败
function getLSGuid () {
	let guid = ''
	try {
		guid = localStorage.getItem(GUID_KEY)
	} catch (err) {
		guid = ''
	}
	return guid
}

function getCookieGuid () {
	let guid = ''
	try {
		guid = $cookie.get(GUID_KEY, {
			domain: 'yangshipin.cn',
			path: '/'
		})
	} catch (err) {
		guid = ''
	}
	return guid
}

function saveLSGuid (guid) {
	if (!guid) { return }
	try {
		localStorage.setItem(GUID_KEY, guid)
	} catch (err) {
		// do nothing
	}
}

function saveCookieGuid (guid) {
	if (!guid) { return }
	try {
		$cookie.set(GUID_KEY, guid, {
			domain: 'yangshipin.cn',
			path: '/',
			expires: 99 * 365
		})
	} catch (err) {
		// do nothing
	}
}

// 生成浏览器唯一id
// 模拟设备唯一id
// 无法存储 guid，视为私密模式, guid 统一为 'private'
function getGuid() {
	let guid = ''
	guid = getLSGuid() || getCookieGuid()
	// 每次获取到 guid 都同步一次 cookie 与 localstorage
	saveLSGuid(guid)
	saveCookieGuid(guid)
	if (!guid) {
		let time = (new Date()).getTime().toString(36)
		let rnd = Math.random().toString(36).replace(/^0./, '')
		guid = time + '_' + rnd
		// 生成后立即存入 cookie 与 localstorage
		saveLSGuid(guid)
		saveCookieGuid(guid)
		// 存完后立即检查是否存入成功
		guid = getLSGuid() || getCookieGuid()
		// 有时无法存入，这意味着用户开启了浏览器私密模式
		if (!guid) {
			guid = 'private'
		}
	}
	return guid
}

export default getGuid
